<template >
  <basiccard :header_nav="header_nav">
    <el-row>
      <el-col>
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>
    <el-table :data="rolesList" stripe border>
      <el-table-column type="expand">
          <template slot-scope="scope">
              <el-row  :class="['bd_bottom','vcenter',i1===0?'btp_top' : '']" v-for="(item, i1) in scope.row.children" :key="item.id">
            <el-col :span="5">
               <el-tag closable type="" @close="removeRightId(scope.row,item.id)">{{item.authName}}</el-tag> 
               <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
                <el-row :class="['vcenter',i2===0?'':'btp_top']" v-for="(item1,i2) in item.children" :key="item1.id">
                  <el-col :span="5">
                      <el-tag closable type="success" @close="removeRightId(scope.row,item1.id)">{{item1.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                      <el-tag closable type="warning" v-for="(item2,i3) in item1.children" :key="item2.id" @close="removeRightId(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  </el-col>
                </el-row>
            </el-col>
          </el-row>
          </template>
         
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editRoles(scope.row.id)"
          >编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
          <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑角色区域 -->
    <el-dialog title="编辑角色" :visible.sync="RolesVisible" width="30%">
      <el-form ref="RoleformRef" :model="roles" :rules="rolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolessub">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 树形控件 -->
    <el-dialog
  title="提示"
  :visible.sync="showRightVisible"
  width="30%"
  @close="setRightclose"
>
  <el-tree :data="rightTree" :props="defaultProps" node-key="id" ref="rightTreeRef"   show-checkbox :default-expand-all="true" :default-checked-keys="defkeys"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="showRightVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </basiccard>
</template>
<script>
export default {
  name: "Character",
  data() {
    return {
      // 传给基础组件的值
      header_nav: {
        path: "/welecome",
        rolesMge: "角色管理",
        rolesList: "角色列表"
      },
      roles: {},
      roleId:'',
      RolesVisible: false,
      showRightVisible:false,
      rightTree:[],
      rolesList: [],
      rolesRules: {
        roleName: [
          { require: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { require: true, message: "请输入角色描述", trigger: "blur" }
        ]
      },
      defkeys:[],
      defaultProps:{
          label:'authName',
          children:'children'
      }
    };
  },
  methods: {
      getLeftkey(node,arr) {
         if(!node.children){
           return arr.push(node.id)
         }
       node.children.forEach(item=>
       this.getLeftkey(item,arr)
       )
      },
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
      console.log(this.rolesList);
    },
    async editRoles(val) {
      const { data: res } = await this.$http.get(`roles/${val}`);
      console.log(res);
      this.roles = res.data;
      this.RolesVisible = true;
    },
  async removeRightId(roles,valId) {
      
       const result =   await  this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(result!=='confirm') return this.$message.error('取消删除')
     const {data:res} =    await this.$http.delete(`roles/${roles.id}/rights/${valId}`)
            if(res.meta.status!==200) return this.$message.error('删除权限失败')
            this.$message.success('删除权限成功')
            // this.getRolesList()
            roles.children = res.data

    },
      editRolessub() {
    this.$refs.RoleformRef.validate(async valid => {
      if (!valid) return;
      const { data: res } = await this.$http.put(`roles/${this.roles.roleId}`, {
        roleName: this.roles.roleName,
        roleDesc: this.roles.roleDesc
      });
      if (res.meta.status !== 200) return this.$message.error("更新失败");
      this.getRolesList();
      this.$message.success("更新成功");
      this.RolesVisible = false
    });
  },
  async showSetRightDialog(role) {
    this.roleId = role.id
    const {data:res}  = await this.$http.get(`rights/tree`)
    console.log(res.data);
        this.rightTree = res.data
       this.getLeftkey(role,this.defkeys)
       console.log(this.defkeys);
       
       this.showRightVisible = true
    
  },
  setRightclose() {
      this.defkeys = []
  },
  async allotRights() {
      const keys = [
     ...this.$refs.rightTreeRef.getCheckedKeys(),
     ...this.$refs.rightTreeRef.getHalfCheckedKeys()]
    const str = keys.join(',')


    const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
         rids:str
    })
    if(res.meta.status!==200) return this.$message.error('权限分配失败')
    this.$message.success('角色分配成功')
    // this.showRightVisible = false
    this.getRolesList()
    this.showRightVisible = false
  }
  },

  created() {
    this.getRolesList();
  }
};
</script>
<style lang="scss" scoped>
.el-tag {
    margin: 10px;
}
.btp_top {
    border-top: 1px solid #ccc;
}
.bd_bottom {
   border-bottom: 1px solid #ccc;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>